package top.waikin.springbootjpa.controller;

import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import top.waikin.springbootjpa.domain.TestVo;
import top.waikin.springbootjpa.entity.Test;
import top.waikin.springbootjpa.repository.TestRepository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author WaiKin
 * @date 2022/11/30
 */
@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    TestRepository testRepository;

    @PostMapping
    public ResponseEntity<Long> create(@RequestBody TestVo testVo) {
        Test test = new Test();
        BeanUtils.copyProperties(testVo, test);
        testRepository.save(test);
        return ResponseEntity.ok(test.getId());
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        testRepository.findById(id).ifPresent(test -> testRepository.deleteById(id));
    }

    @DeleteMapping("/{id}")
    public void update(@PathVariable Long id, @RequestBody TestVo testVo) {
        testRepository.findById(id).ifPresent(test -> {
            BeanUtils.copyProperties(testVo, test);
            testRepository.save(test);
        });
    }

    @GetMapping("/{id}")
    public ResponseEntity<Test> getById(@PathVariable Long id) {
        Optional<Test> byId = testRepository.findById(id);
        return ResponseEntity.of(byId);
    }

    @GetMapping
    public ResponseEntity<List<Test>> getAll() {
        List<Test> all = testRepository.findAll();
        return ResponseEntity.ok(all);
    }

    @GetMapping("/page")
    public ResponseEntity<Page<Test>> page(Pageable pageable) {
        Page<Test> page = testRepository.findAll(pageable);
        return ResponseEntity.ok(page);
    }
}
